﻿using System;
using System.Diagnostics;

using Builderator.Core.Plugin;
using Builderator.Core.Interfaces;

namespace Builderator.Core.Action
{
    public class MSBuildPlugin : PluginBase, ICompile
    {
        [DocumentProperty("Executable", typeof(Uri), false, DocumentProperty.BrowseUriType.File, "Executable|*.exe")]
        public string Executable
        {
            get;
            set;
        }

        [DocumentProperty("Project File", typeof(Uri), false, DocumentProperty.BrowseUriType.File, "Project/Solution File|*.csproj;*.sln")]
        public string Project
        {
            get;
            set;
        }

        [DocumentProperty("Output", typeof(Uri), false, DocumentProperty.BrowseUriType.Folder, "")]
        public string Output
        {
            get;
            set;
        }

        public MSBuildPlugin()
            : base("MSBuild", new Guid("1479B40A-E3E8-11E0-96AF-67DF4824019B"))
        {

        }

        public override ExecutionResult Run()
        {
            Process process = new Process();

            process.StartInfo.Arguments = string.Format("{0} /property:OutDir={1}", this.Project, this.Output);
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.FileName = this.Executable;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute = false;

            process.EnableRaisingEvents = true;
            process.Exited += new EventHandler(process_Exited);

            process.Start();

            this.DebugMessage(process.StandardOutput);

            return base.Run();
        }

        private void process_Exited(object sender, EventArgs e)
        {
            this.Running = false;

            this.ExitCode = ((Process)sender).ExitCode;
        }
    }
}